import { t } from 'i18next'
import { useState, useEffect } from 'react'
import { fetchOps } from '@/api/manager/helper'
import { ICheckingItem } from '@/api/manager/helper/interface'
import { useRequest } from 'ahooks'
import dayjs from '@/plugins/dayjs'

function transCheckingList(list: ICheckingItem[]) {
	let _obj: { [key: string]: true } = {},
		result: ICheckingItem[] = []
	list.map((cur) => ({ ...cur, event_time: dayjs(cur.event_time).format('YYYY-MM-DD HH:mm:ss') }))
		.sort((a, b) => dayjs(b.event_time).unix() - dayjs(a.event_time).unix())
		.forEach((x) => {
			const { mt_e164, type } = x
			if (_obj[`${mt_e164}$$${type}`]) {
			} else {
				_obj[`${mt_e164}$$${type}`] = true
				result.push(x)
			}
		})
	return result
}

export const useData = () => {
	const [list, setList] = useState<ICheckingItem[]>([])
	const [errorText, setErrorText] = useState<string | null>(null)
	const { loading, data, run } = useRequest(fetchOps, { manual: true })
	useEffect(() => {
		if (!loading) {
			if (data) {
				const list = transCheckingList(data)
				setList(list)
				setErrorText(null)
			} else {
				setErrorText(t('会议大数据服务器异常，请稍后重试'))
			}
		}
	}, [data])
	return { list, run, errorText, loading }
}
